package com.qmzy.lab05.service.impl;

import com.qmzy.lab05.entity.Account;
import com.qmzy.lab05.service.IAccountService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private IAccountService iAccountService;
    private PasswordEncoder pw=new BCryptPasswordEncoder();


    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
//        System.out.println("进到loadUserByUsername里了");
        Account oneByid = iAccountService.getById(Integer.parseInt(username));//iAccountService.getOneByid(Integer.parseInt(username));
        if(oneByid==null){
            throw new UsernameNotFoundException("用户名不存在!");
        }
        return new User(username,pw.encode(oneByid.getPassword()),true,true,true,!(oneByid.getAclock()==1),AuthorityUtils.commaSeparatedStringToAuthorityList(oneByid.getRole()));
    }


    public void updateUser(User updated) {
        Account oneByid = iAccountService.getById(Integer.parseInt(updated.getUsername()));
        oneByid.setAclock(1);
        iAccountService.updateById(oneByid);
    }
}
